#!/usr/bin/perl
use CGI;
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use strict;
use Digest::MD5 qw(md5 md5_hex md5_base64);
my $readin;
read(STDIN, $readin, $ENV{'CONTENT_LENGTH'});
my $inputstring = $readin;
my $schar = substr($inputstring, 1, 1);
my %hash = ();
if($ENV{'CONTENT_LENGTH'}.length() < 1){
#####If nothing is typed right now.#####
	print "Content-type: text/html\n\n";
	
	open (FILE,"password.html");
	while (<FILE>) {
		print $_;
	}
	close(FILE);
print <<END_OF_PRINTING; 
END_OF_PRINTING
}
#password reset script
elsif ($schar ne 's'){
	print "Content-type: text/html\n\n";
	my ($pairs,$key,$value);
	my @pairsarr = split(/&/, $inputstring);
	foreach my $pairs (@pairsarr){
		my @keyvalue = split(/=/, $pairs);
		$key = $keyvalue[0];
		$value = $keyvalue[1];
		$hash{ $key } = $value;
	}
	
	my $username = $hash{"LoginForm%5BEmail%5D"};
		
	my $password = md5_hex(rand() . "\n");
	$password = substr $password, 0, 10;	
	my $encodedpass = md5_hex($password);
	open FP, "password.txt";
	my @lines = <FP>;
	my @fields;
	my $namename;
	foreach my $line (@lines){
		@fields = split /[ ]*,[ ]*/, $line;
		if ($fields[0] eq $username){
			$line = "$username,$encodedpass,$fields[2]";
			$namename = $fields[2];
		}
	}
	close FP;
	open FP, ">", "password.txt";
	print FP @lines;
	close FP;
	$username =~ s/%([\da-f][\da-f])/chr( hex($1) )/egi;
	my $email = $username;
	#if email satisfies [something]@[something].[something of length 2-6]
	#if ($email =~ /[\w._+-]+@[\w.-]+\.[A-Z]{2,6}/i){
	#just to make sure you have a body
	$username =~ s/@/at/g;
	print $username;
	open (MYFILE, ">>password.txt");
	print "\n\n";
	my $enter = $username.",".md5_hex($password).",".$namename;
	print MYFILE $enter;
	print MYFILE "\n";
	close (MYFILE);
	if (length($email) > 0){
		#send email
		open(MAIL, "|mail -s \"AP script\" $email")
		  || die "Failed mailing";
		print MAIL "$username: $password";
		close(MAIL);
		print "E-mail sent to $email.\n";
	}
	else {
		print "No e-mail body.";
	}
}
